<?php
namespace wstmart\admin\model;
use think\Db;
use think\Loader;
/**
 * ============================================================================
 * WSTMart多用户商城
 * 版权所有 2016-2066 广州商淘信息科技有限公司，并保留所有权利。
 * 官网地址:http://www.wstmart.net
 * 交流社区:http://bbs.shangtao.net
 * 联系QQ:153289970
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 任务处理
 */
class Renwu extends Base{
	/**
	 * 分页
	 */
	public function pageQuery($shopStatus=1){
//		dump($_SESSION);
		$uid  = $_SESSION['WSTMART_']['WST_STAFF']['staffId'];
		$opt = [];

		$opt['shangjiaid'] = $uid;
		if(!empty(input('taobao'))){
			$opt['taobao'] = input('taobao');
		}
		if(!empty(input('star_time') && !empty(input('end_time')))){
			$opt['fangdanshijian'] = ['between',[strtotime(input('star_time')),strtotime(input('end_time'))]];
		}

//		dump($opt);
		$data = Db::name('renwu')
			->where($opt)
			->order('id desc')->paginate(input('pagesize/d'));
//		dump($data);
//		foreach($data['Rows'] as $k=>$v){
//			$data['Rows'][$k]['fangdanshijian'] = 1;
//		}
//		dump($data);
//		$data = json_encode($data);


		return $data;
	}
	/*查询任务数据*/
	public function getRenwu($id){
		if(!$id){
			return '';
		}
		return Db::name('renwu')->where('id',$id)->find();
	}
	/**
	 * 删除
	 */
    public function del(){
		$id = input('post.id/d');
		if($id){
			if(Db::name('renwu')->where('id',$id)->delete()!=false){
				return WSTReturn("删除成功", 1);
			}else{
				return WSTReturn('删除失败',-1);
			}
		}
		die;

		$data = [];
		$data['dataFlag'] = -1;
	    Db::startTrans();
        try{
	        $result = $this->update($data,['shopId'=>$id]);
	        WSTUnuseImage('shops','shopImg',$id);
            if(false !== $result){
            	//删除推荐店铺
            	Db::name('recommends')->where(['dataSrc'=>1,'dataId'=>$id])->delete();
            	//下架商品
        	    model('goods')->unsaleByshopId($id);
        	    return WSTReturn("删除成功", 1);
            }
        }catch (\Exception $e) {
            Db::rollback();
        }
        return WSTReturn('删除失败',-1);
	}
	
	/**
	 * 获取店铺信息
	 */
	public function getById($id){
		$shop = $this->get(['dataFlag'=>1,'shopId'=>$id])->toArray();
		//获取经营范围
		$goodscats = Db::name('cat_shops')->where('shopId',$id)->select();
		$shop['catshops'] = [];
		foreach ($goodscats as $v){
			$shop['catshops'][$v['catId']] = true;
		}
		//获取认证类型
	    $shopAccreds = Db::name('shop_accreds')->where('shopId',$id)->select();
	    $shop['accreds'] = [];
		foreach ($shopAccreds as $v){
			$shop['accreds'][$v['accredId']] = true;
		}
		return $shop;
	}
	/**
	 * 生成店铺编号
	 * @param $key 编号前缀,要控制不要超过int总长度，最好是一两个字母
	 */
	public function getShopSn($key = ''){
		$rs = $this->Max("REPLACE(shopSn,'S','')+''");
		if($rs==''){
			return $key.'000000001';
		}else{
			for($i=0;$i<1000;$i++){
			   $num = (int)str_replace($key,'',$rs);
			   $shopSn = $key.sprintf("%09d",($num+1));
			   $ischeck = $this->checkShopSn($shopSn);
			   if(!$ischeck)return $shopSn;
			}
			return '';//一直都检测到那就不要强行添加了
		}
	}
	
	/**
	 * 检测店铺编号是否存在
	 */
	public function checkShopSn($shopSn,$shopId=0){
		$dbo = $this->where(['shopSn'=>$shopSn,'dataFlag'=>1]);
		if($shopId>0)$dbo->where('shopId','<>',$shopId);
		$num = $dbo->Count();
		if($num==0)return false;
		return true;
	}
	

	/**
	 * 新增
	 */
	public function add(){
		$data = input('post.');
		$data['fangdanshijian2'] = $data['fangdanshijian'];
		$data['fangdanshijian'] = strtotime($data['fangdanshijian']);
		$data['shangjiaid'] = $_SESSION['WSTMART_']['WST_STAFF']['staffId'];
		if( Db::name('renwu')->insert($data) != false){
			return WSTReturn("新增成功", 1);
		}else{
			return WSTReturn("新增失败", -1);
		}
	}
    /**
	 * 编辑
	 */
	public function edit(){
            $id = input('post.id/d',0);
			$data = input('post.');
		    $data['fangdanshijian2'] = $data['fangdanshijian'];
		    $data['fangdanshijian'] = strtotime($data['fangdanshijian']);
			if( Db::name('renwu')->where('id',$id)->update($data)!=false ){
				return WSTReturn("新增成功", 1);
			}else{
				return WSTReturn("编辑失败", -1);
			}
	}
	/**
	* 获取所有店铺id
	*/
	public function getAllShopId(){
		return $this->where(['dataFlag'=>1,'shopStatus'=>1])->column('shopId');
	}
	
	/**
	 * 搜索经验范围的店铺
	 */
	public function searchQuery(){
		$goodsCatatId = (int)input('post.goodsCatId');
		if($goodsCatatId<=0)return [];
		$key = input('post.key');
		$where = [];
		$where['dataFlag'] = 1;
		$where['shopStatus'] = 1;
		$where['catId'] = $goodsCatatId;
		if($key!='')$where['shopsName|shopSn'] = ['like','%'.$key.'%'];
		return $this->alias('s')->join('__CAT_SHOPS__ cs','s.shopId=cs.shopId','inner')
		            ->where($where)->field('shopName,s.shopId,shopSn')->select();
	}
	
    /**
	 * 自营自动登录
	 */
	public function selfLogin($id){
		$shopId = $id;
		$userid = $this->where(["dataFlag"=>1, "shopStatus"=>1,"shopId"=>$shopId])->field('userId')->find();
		if(!empty($userid['userId'])){
			$userId = $userid['userId'];
			//获取用户信息
			$u = new Users();
			$rs = $u->getById($userId);
			//获取用户等级
			$rrs = Db::name('user_ranks')->where('startScore','<=',$rs['userTotalScore'])->where('endScore','>=',$rs['userTotalScore'])->field('rankId,rankName,userrankImg')->find();
			$rs['rankId'] = $rrs['rankId'];
			$rs['rankName'] = $rrs['rankName'];
			$rs['userrankImg'] = $rrs['userrankImg'];
			$ip = request()->ip();
			$u->where(["userId"=>$userId])->update(["lastTime"=>date('Y-m-d H:i:s'),"lastIP"=>$ip]);
			//加载店铺信息
			$shops= new Shops();
			$shop = $shops->where(["userId"=>$userId,"dataFlag" =>1])->find();
			if(!empty($shop))$rs = array_merge($shop->toArray(),$rs->toArray());
			//记录登录日志
			$data = array();
			$data["userId"] = $userId;
			$data["loginTime"] = date('Y-m-d H:i:s');
			$data["loginIp"] = $ip;
			Db::name('log_user_logins')->insert($data);
			session('WST_USER',$rs);
			return WSTReturn("","1");
		}
		return WSTReturn("",-1);
	}
	
	/**
	 * 导出订单
	 */
	public function toExport(){
		$name='任务表';
		$uid  = $_SESSION['WSTMART_']['WST_STAFF']['staffId'];
		$opt = [];
		$opt = [
			'shangjiaid'=>$uid
		];
		$page = Db::name('renwu')->where($opt)->order('id desc')->select();


		foreach($page as $k=>$v){
			$page2[] = $page[$k];
			$page2[] = [
				'id'=>'',
				'taobao'=>'',
				'danjia'=>'',
				'lurujine'=>'',
				'dingdanbianhao'=>'',
				'guanjianci'=>'',
				'fangdanshijian2'=>'',
				'dianpu'=>'',
				'shangjia'=>'',
				'dianpulianjie'=>'',
				'shangjiabeizhu'=>'',
			];
		}
		$page = $page2;
//		dump($page2);die;
//		$where = ['o.dataFlag'=>1];
//		$orderStatus = (int)input('orderStatus',0);
//		if($orderStatus==0){
//			$name='待发货订单表';
//		}else if($orderStatus==-2){
//			$name='待付款订单表';
//		}else if($orderStatus==1){
//			$name='配送中订单表';
//		}else if($orderStatus==10000){
//			$name='订单列表';
//		}else if($orderStatus==-1){
//			$name='取消订单表';
//		}else if($orderStatus==-3){
//			$name='拒收订单表';
//		}else if($orderStatus==2){
//			$name='已收货订单表';
//		}
//		if($orderStatus!=10000){
//			$where['o.orderStatus'] = $orderStatus;
//		}
//		$orderNo = input('orderNo');
//		$shopName = input('shopName');
//		$payType = (int)input('payType',-1);
//		$deliverType = (int)input('deliverType',-1);
//		if($orderNo!='')$where['orderNo'] = ['like','%'.$orderNo.'%'];
//		if($shopName!='')$where['shopName|shopSn'] = ['like','%'.$shopName.'%'];
//
//		$areaId1 = (int)input('areaId1');
//		if($areaId1>0){
//			$where['s.areaIdPath'] = ['like',"$areaId1%"];
//			$areaId2 = (int)input("areaId1_".$areaId1);
//			if($areaId2>0)$where['s.areaIdPath'] = ['like',$areaId1."_"."$areaId2%"];
//			$areaId3 = (int)input("areaId1_".$areaId1."_".$areaId2);
//			if($areaId3>0)$where['s.areaId'] = $areaId3;
//		}
//
//		if($deliverType!=-1)$where['o.deliverType'] = $deliverType;
//		if($payType!=-1)$where['o.payType'] = $payType;
//		$page = $this->alias('o')->where($where)
//			->join('__SHOPS__ s','o.shopId=s.shopId','left')
//			->join('__LOG_ORDERS__ lo','lo.orderId=o.orderId and lo.orderStatus in (-1,-3) ','left')
//			->field('o.orderId,o.orderNo,s.shopName,s.shopId,s.shopQQ,s.shopWangWang,o.goodsMoney,o.totalMoney,o.realTotalMoney,o.deliverMoney,lo.logContent
//		              ,o.orderStatus,o.userName,o.userAddress,o.userPhone,o.orderRemarks,o.invoiceClient,o.receiveTime,o.deliveryTime,o.deliverType,payType,payFrom,o.orderStatus,orderSrc,o.createTime')
//			->order('o.createTime', 'desc')
//			->select();
//		if(count($page)>0){
//			foreach ($page as $key => $v){
//				$page[$key]['payTypeName'] = WSTLangPayType($v['payType']);
//				$page[$key]['deliverType'] = WSTLangDeliverType($v['deliverType']==1);
//				$page[$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
//			}
//		}
		Loader::import('phpexcel.PHPExcel.IOFactory');
		$objPHPExcel = new \PHPExcel();
		// 设置excel文档的属性
		$objPHPExcel->getProperties()->setCreator("js")//创建人
		->setLastModifiedBy("js")//最后修改人
		->setTitle($name)//标题
		->setSubject($name)//题目
		->setDescription($name)//描述
		->setKeywords("任务")//关键字
		->setCategory("Test result file");//种类

		// 开始操作excel表
		$objPHPExcel->setActiveSheetIndex(0);
		// 设置工作薄名称
		$objPHPExcel->getActiveSheet()->setTitle(iconv('gbk', 'utf-8', 'Sheet'));
		// 设置默认字体和大小
		$objPHPExcel->getDefaultStyle()->getFont()->setName(iconv('gbk', 'utf-8', ''));
		$objPHPExcel->getDefaultStyle()->getFont()->setSize(11);
		$styleArray = array(
			'font' => array(
				'bold' => true,
				'color'=>array(
					'argb' => 'ffffffff',
				)
			),
			'borders' => array (
				'outline' => array (
					'style' => \PHPExcel_Style_Border::BORDER_THIN,  //设置border样式
					'color' => array ('argb' => 'FF000000'),     //设置border颜色
				)
			)
		);
		//设置宽
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);

		$objPHPExcel->getActiveSheet()->getStyle('A1:P1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle('A1:P1')->getFill()->getStartColor()->setARGB('333399');

		$objPHPExcel->getActiveSheet()->setCellValue('A1', 'id')->setCellValue('B1', '淘宝名')->setCellValue('C1', '单价')->setCellValue('D1', '管理员录入金额')->setCellValue('E1', '订单编号')
			->setCellValue('F1', '关键词')->setCellValue('G1', '放单时间')->setCellValue('H1', '店铺')->setCellValue('I1', '商家')->setCellValue('J1', '店铺链接')->setCellValue('K1', '商家备注');
		$objPHPExcel->getActiveSheet()->getStyle('A1:P1')->applyFromArray($styleArray);

		for ($row = 0; $row < count($page); $row++){
			$i = $row+2;
			$objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $page[$row]['id'])->setCellValue('B'.$i, $page[$row]['taobao'])->setCellValue('C'.$i, $page[$row]['danjia'])->setCellValue('D'.$i, $page[$row]['lurujine'])
				->setCellValue('E'.$i, $page[$row]['dingdanbianhao'])->setCellValue('F'.$i, $page[$row]['guanjianci'])->setCellValue('G'.$i, $page[$row]['fangdanshijian2'])->setCellValue('H'.$i, $page[$row]['dianpu'])
				->setCellValue('I'.$i, $page[$row]['shangjia'])->setCellValue('J'.$i, $page[$row]['dianpulianjie'])->setCellValue('K'.$i, $page[$row]['shangjiabeizhu']);
		}

		//输出EXCEL格式
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		// 从浏览器直接输出$filename
		header('Content-Type:application/csv;charset=UTF-8');
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Content-Type:application/force-download");
		header("Content-Type:application/vnd.ms-excel;");
		header("Content-Type:application/octet-stream");
		header("Content-Type:application/download");
		header('Content-Disposition: attachment;filename="'.$name.'.xls"');
		header("Content-Transfer-Encoding:binary");
		$objWriter->save('php://output');
	}
	/**
	 * 上传商品数据
	 */
	public function importGoods($data){
		Loader::import('phpexcel.PHPExcel.IOFactory');
		$objReader = \PHPExcel_IOFactory::load(WSTRootPath().json_decode($data)->route.json_decode($data)->name);
		$objReader->setActiveSheetIndex(0);
		$sheet = $objReader->getActiveSheet();
		$rows = $sheet->getHighestRow();
		$cells = $sheet->getHighestColumn();
		//数据集合
		$readData = [];
//		$shopId = (int)session('WST_USER.shopId');
		$importNum = 0;
//		$goodsCatMap = []; //记录最后一级商品分类
//		$goodsCatPathMap = [];//记录商品分类路径
//		$shopCatMap = [];//记录店铺分类
//		$goodsCat1Map = [];//记录最后一级商品分类对应的一级分类
//		$tmpGoodsCatId = 0;
//		$goodsCatBrandMap = [];//商品分类和品牌的对应关系
		//生成订单
		Db::startTrans();
		try{
			//循环读取每个单元格的数据
			for ($row = 2; $row <= $rows; $row++){//行数是以第2行开始

				$goods['taobao'] = trim($sheet->getCell("B".$row)->getValue());
				$goods['danjia'] = trim($sheet->getCell("C".$row)->getValue());
				$goods['lurujine'] = trim($sheet->getCell("D".$row)->getValue());
				$goods['dingdanbianhao'] = trim($sheet->getCell("E".$row)->getValue());
				$goods['guanjianci'] = trim($sheet->getCell("F".$row)->getValue());
				$goods['fangdanshijian2'] = trim($sheet->getCell("G".$row)->getValue());
				$goods['dianpu'] = trim($sheet->getCell("H".$row)->getValue());
				$goods['shangjia'] = trim($sheet->getCell("I".$row)->getValue());
				$goods['dianpulianjie'] = trim($sheet->getCell("J".$row)->getValue());
				$goods['shangjiabeizhu'] = trim($sheet->getCell("K".$row)->getValue());
				$goods['fangdanshijian'] = strtotime(trim($sheet->getCell("G".$row)->getValue()));
				$goods['shangjiaid'] = $_SESSION['WSTMART_']['WST_STAFF']['staffId'];
				$readData[]  = $goods;
				$importNum++;
			}

			
			if(count($readData)>0){
				// 如果订单重复 就更新

				Db::name('renwu')->insertAll($readData);
			}
			Db::commit();
			return json_encode(['status'=>1,'importNum'=>$importNum]);
		}catch (\Exception $e) {
			Db::rollback();
			return json_encode(WSTReturn('导入商品失败',-1));
		}
	}
}
